package com.bms.admin.base.role.web;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bms.admin.base.index.model.NowUser;
import com.bms.admin.base.role.entity.Role;
import com.bms.admin.base.role.service.IRoleMenuService;
import com.bms.admin.base.role.service.IRoleService;
import com.bms.admin.base.role.vo.RoleVo;
import com.bms.admin.base.user.entity.User;
import com.bms.admin.base.user.service.IUserService;
import com.bms.admin.config.annotation.LoginUser;
import com.bms.auth.annotation.RequiresPermissions;
import com.bms.common.base.common.bean.Result;
import com.bms.common.base.common.exception.EnumSvrResult;
import com.bms.common.base.web.BaseController;
import com.feilong.core.Validator;
import com.feilong.core.bean.ConvertUtil;
import com.feilong.core.util.CollectionsUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * <p>
 * 角色  前端控制器
 * </p>
 *
 * @author xj
 * @since 2018-08-09
 */
@RestController
@RequestMapping("role")
@Api(value="Role-Api",tags="角色管理")
public class RoleController extends BaseController {

	@Autowired
	private IRoleService roleService;

	@Autowired
	private IUserService userService;

	@Autowired
	private IRoleMenuService roleMenuService;

	@ApiOperation("获取角色列表")
	@GetMapping("list")
	@RequiresPermissions("role:list")
    public Result list(@ApiIgnore @LoginUser NowUser nowUser,@RequestParam(defaultValue = "1",required=false)Integer pageNum, @RequestParam(defaultValue = "20",required=false)Integer pageSize,@RequestParam(required=false) String name) {
		EntityWrapper<RoleVo> ew = new EntityWrapper<>();
		if(Validator.isNotNullOrEmpty(name)){
			ew.like("role_name", name);
		}
		if(nowUser.getUserId()!=1){
			ew.eq("company_id", nowUser.getCompanyId());
		}
		ew.orderBy("create_time", false);
		return json(roleService.selectRoleList(new Page<RoleVo>(pageNum,pageSize),ew));
    }

	@GetMapping("select")
    public Result select(@ApiIgnore @LoginUser NowUser nowUser,@RequestParam Long companyId ) {
		EntityWrapper<Role> ew = new EntityWrapper<>();
		if(nowUser.getUserId()!=1){
			ew.eq("company_id", nowUser.getCompanyId());
		}else{
			ew.eq("company_id", companyId);
		}
		return json(roleService.selectList(ew));
	}

	@ApiOperation("获取角色信息")
	@GetMapping("info/{roleId}")
	@RequiresPermissions("role:info")
    public Result select(@PathVariable Long roleId){
		Role role = roleService.selectById(roleId);
		List<Long> menuIds = roleMenuService.selectMenuIdsByRoleId(roleId);
		role.setMenuIdList(menuIds);
		return json(role);
    }

	@ApiOperation("新增角色")
	@PostMapping("save")
	@RequiresPermissions("role:save")
	public Result save(@ApiIgnore @LoginUser NowUser nowUser,@Validated @RequestBody Role role){
		
		EntityWrapper<Role> ew = new EntityWrapper<>();
		ew.eq("role_name", role.getRoleName());
		ew.eq("company_id", role.getCompanyId());
		if(Validator.isNotNullOrEmpty(roleService.selectOne(ew))){
			return fail(EnumSvrResult.ERROR_DEL_ROLE);
		}
		
		Date now = new Date();
		role.setCreateTime(now);
		role.setCreateUser(nowUser.getUsername());
		role.setUpdateTime(now);
		roleService.insert(role);

		if (!CollectionUtils.isEmpty(role.getMenuIdList())) {
			roleService.savePermission(role.getId(), role.getMenuIdList());
		}

		return success();
	}

	@ApiOperation("修改角色信息")
	@PostMapping("update")
	@RequiresPermissions("role:update")
	public Result update(@ApiIgnore @LoginUser NowUser nowUser,@Validated @RequestBody Role role){
		EntityWrapper<Role> ew = new EntityWrapper<>();
		ew.eq("role_name", role.getRoleName());
		ew.eq("company_id", role.getCompanyId());
		ew.ne("id", role.getId());
		if(Validator.isNotNullOrEmpty(roleService.selectOne(ew))){
			return fail(EnumSvrResult.ERROR_DEL_ROLE);
		}
		
		role.setUpdateTime(new Date());
		role.setUpdateUser(nowUser.getUsername());
		roleService.updateById(role);

		roleService.savePermission(role.getId(), role.getMenuIdList());
		return success();
	}

	@ApiOperation("删除角色")
	@DeleteMapping("delete")
	@RequiresPermissions("role:delete")
    public Result delete(@RequestBody List<Long> roleIds) {
		List<User> users = userService.selectList(new EntityWrapper<User>().in("role_id", roleIds));
		if(Validator.isNotNullOrEmpty(users)){
			return fail(EnumSvrResult.ERROR_DEL_ROLE);
		}
		roleService.deleteBatchIds(roleIds);
		roleMenuService.deleteByRoleIds(roleIds);
		return success();
    }

	@ApiOperation("角色分配资源")
	@PostMapping("permission")
	@RequiresPermissions("role:permission")
	public Result permission(@RequestParam Long roleId, @RequestBody List<Long> menuIds){
		roleService.savePermission(roleId,menuIds);
		return success();
	}

	@ApiOperation("获取角色资源")
	@PostMapping("getPermission/{roleId}")
	@RequiresPermissions("role:getPermission")
	public Result getPermission(@PathVariable Long roleId){
		return json(CollectionsUtil.getPropertyValueList(roleMenuService.selectByMap(ConvertUtil.toMap("role_id",roleId)), "menuId"));
	}
}
